<?php
/*
thinkPHP v5.0
v0.03
2017-02-14 bach
*/
namespace app\common\model;
use think\Session;

class User{

    // 变量
    private $user;
    private $config = [
        'SESSION_INFO' => true,
        'AUTO_LOGIN' => false,
    ];
    private $appIndex;
    private $password_reg = "/((?=.*\d)(?=.*\D)|(?=.*[a-zA-Z])(?=.*[^a-zA-Z]))^.{8,16}$/";
    private $tel_reg = "";
    private $email_reg = "";
    private $method = array('tel','openid','email');
    private $a;
    // ------------------------------------------------- 基础支持函数 -------------------------------------------------
    // ------------------------------------------------- 基础支持函数 -------------------------------------------------
    // ------------------------------------------------- 基础支持函数 -------------------------------------------------
    // ------------------------------------------------- 基础支持函数 -------------------------------------------------
    // ------------------------------------------------- 基础支持函数 -------------------------------------------------
    public function __construct() {
        $wechat_account = config('wechat');
        $this->appIndex = $wechat_account['APP_INDEX'];
        if(isset($_SERVER['HTTP_REFERER'])&&$_SERVER['HTTP_REFERER']){
            $this->a = $_SERVER['HTTP_REFERER'];
        }
        if ($this->user && $this->user['user_id']) {
            return;
        }
        //如果已经登陆，则从数据库取出用户数据
        if ($this->logined()) {
            if($this->config['SESSION_INFO']){
                $this->user = session('user');
                if(!isset($this->user['user_name'])){
                    $this->info();
                    $this->session_set();
                    return;
                }
            }
            $this->info();
            return;
        }
        //如果拥有auto COOKIE则启动自动登陆
//        $cookie = json_decode(cookie('auto'), true);
//        if ($cookie) {
//            $res = $this->login($demand = 'auto');
//            if (!$res['state']) {
//                return;
//            }
//            $this->info();
//        }
    }
    // 放置session 重新加载session
    function refresh(){
        $this->session_set();
    }
    private function session_set($user = null) {
        if(!$user){
            $user = $this->user;
        }
        if (!$user || !$user['user_id']) {
            return 0;
        }
        session("user",["user_id"=>$user["user_id"]]);
        if($this->config['SESSION_INFO']){
            $info = $this->info($reload = true);
            // if(!isset($info['data']) || !$info['data'] ){
            // session("user",null);
            // return 0;
            // }
            if(isset($user['auto']) && $user['auto']){
                session(["user"=>$info['data'],'expire'=>86400*7,'prefix'=>'hyc','auto_start'=>true,'domain'=>'.hongyanche.com']);
                cookie("PHPSESSID", session_id(), 3600 * 7 * 24);
            }else{
                session("user",$info['data']);
                cookie("PHPSESSID", session_id());
            }
        }
        return $user['user_id'];
    }
    // 是否存在user 返回$user_id
    public function exist($info){
        foreach ($this->method as $k) {
            if(!isset($info[$k])){
                continue;
            }else{
                $method = $info[$k];
                $where = array($k=>$method,'state'=>1);
                if($k == 'openid'){
                    $where['app_index'] = $this->appIndex;
                }
                $where = array_change_key_case($where,CASE_LOWER);
                $res = db('user_'.$k)->where($where)->find();
                if(!$res){
                    return array('state'=>0,'errormsg'=>'user not exist');
                }
                return array('state'=>1,'data'=>array('user_id'=>$res['user_id']));
            }
        }
        return array('state'=>0,'errormsg'=>'method error');
    }
    // 创建新的用户
    private function newUser($user) {
        // user数据不正确
        if (!$user || !(isset($user['openid']) || isset($user['tel']) || isset($user['email'] ))) {
            return 0;
        }
        $user['join_time'] = time();
        //新建用户账号时生成的随机码(当前时间戳加随机4位英文);
        $str = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
        // dump(!$rand_id && $rand_id_exist);
        $rand_id_exist = true;
        while((!isset($rand_id) || !$rand_id) && $rand_id_exist){
            $rand_id = substr(str_shuffle($str), 0, 32);
            $rand_id_exist = db('user')->where(array('rand_id'=>$rand_id))->find();
        }
        $user['rand_id'] = $rand_id;
        $user['from'] = session('from');
        $user_add = array_change_key_case($user, CASE_LOWER);
        $user_id = db('user')->insertGetId($user_add);
        if(!$user_id){
            return array('state'=>0,'errormsg'=>'new user database save error');
        }
        foreach ($this->method as $method) {
            if(!isset($user[$method])){
                continue;
            }
            $new = array(
                $method     =>$user[$method],
                'create_time' => time(),
                'state'       => 1,
                'user_id'     => $user_id,
                'app_index'   => $this->appIndex,
            );
            $new = array_change_key_case($new,CASE_LOWER);
            db('user_'.$method)->insert($new);
        }
        $user['user_id'] = $user_id;
        $this->session_set($user);
        // $this->session_set();
        // dump($_SESSION);
        // dump($this->user);
        return $user_id;
    }
    private function bindingWX($user_id,$wx_user_id){
        if(!$user_id || !$wx_user_id){
            return array('state'=>0,'errormsg'=>'id missing');
        }
        $openid = $this->getOpenId($wx_user_id);
        $res = db('user_openid')->where(array('openid'=>$openid))->update(array('state'=>0));
        if(!$res){
            return array('state'=>0,'errormsg'=>'old openid database save error');
        }
        $add = array(
            'state' => 1,
            'user_id' => $user_id,
            'create_time' => time(),
            'app_index' => $this->appIndex,
            'openid' => $openid,
        );
        $res = db('user_openid')->insert($add);
        if(!$res){
            return array('state'=>0,'errormsg'=>'new openid database save error');
        };
        $wxInfo = db('user')->where(array('user_id'=>$wx_user_id))->find();
        foreach (array('nickname','headimgurl','country','province','city','district','sex','subscribe','subscribe_time') as $value) {
            $save[$value] = $wxInfo[$value];
        }
        $save = array_change_key_case($save,CASE_LOWER);
        $res = db('user')->where(array('user_id'=>$user_id))->update($save);
        return array('state'=>1);
    }
    // 绑定相关信息
    private function binding($info){
        $user_id = $this->getUserId();
        if(!$user_id){
            return array('state'=>0,'errormsg'=>'user_id error');
        }
        $methodAllow = array('wx_user_id','tel','email');
        foreach ($methodAllow as $mtd) {
            if(isset($info[$mtd])){
                $method = $mtd;
                break;
            }
        }
        if(!$method){
            return array('state'=>0,'errormsg'=>'method incorrect','data'=>$methodAllow);
        }
        //如果本用户已有相关数据 则告知已绑定
        $userInfo = $this->info()['data'];
        $mm = ($method == 'wx_user_id')?'openid':$method;
        if(isset($userInfo[$mm]) && $userInfo[$mm]){
            return array('state'=>0,'errormsg'=>'already has '.$mm);
        }
        //获取了方式 $method 与值$value
        $value = $info[$method];
        //如果是扫码绑定微信的情况
        if($method == 'wx_user_id'){
            $wx_user_id = $value;
            // dump($value);
            $wx_user = $this->getInfoById($wx_user_id);
            // dump($wx_user);
            if(!$wx_user){
                return array('state'=>0,'errormsg'=>'wx user error');
            }
            if(isset($wx_user['tel']) || isset($wx_user['email'])){
                return array('state'=>0,'errormsg'=>'wechat already binding');
            }
            //绑定微信确认成功 开始转移数据
            $res = $this->bindingWX($user_id,$wx_user_id);
            if(!$res['state']){
                return $res;
            }
            $this->session_set();
            return array('state'=>1,'wx_binding'=>1);
        }
        //如果传入的是tel或者email
        //如果目标已经存在
        $method_user_exist = $this->exist($info);
        if($method_user_exist['state']){
            //如果已经存在得有电话或者邮箱 即拒绝
            if(isset($userInfo['tel']) || isset($userInfo['email'])){
                return array('state'=>0,'errormsg'=>"$method exist");
            }
            //确定当前账号是一个空的微信临时账户 则复制本账号微信内容至新账号下
            //绑定微信确认成功 开始转移数据
            $method_user_exist_id = $method_user_exist['data']['user_id'];
            $res = $this->bindingWX($method_user_exist_id,$user_id);
            if(!$res['state']){
                return $res;
            }
            $this->session_set(array('user_id'=>$method_user_exist_id));
            return array('state'=>1,'wx_binding'=>1);
        }
        //如果是tel和email未绑定
        $add = array(
            'STATE'       => 1,
            'USER_ID'     => $user_id,
            'CREATE_TIME' => time(),
            $method     => $value,
        );
        $add = array_change_key_case($add,CASE_LOWER);
        $res = db('user_'.$method)->insert($add);
        if(!$res){
            return array('state'=>0,'errormsg'=>"$value add database error");
        }
        $this->session_set(array('user_id'=>$user_id));
        return array('state'=>1,'binding'=>1);
    }
    // 判断是否自动登录
    private function isAuto($auto) {
        if ($auto) {
            $autoToken = D('Token')->save($demand = 'autoLogin', $data = array(
                'user_id' => $this->user['user_id'],
            ));
            if ($autoToken['state']) {
                $auto = array('token' => $autoToken['data']['code']);
                $auto = json_encode($auto, 1);
                cookie("auto", $auto, 3600 * 7 * 24);
                return 1;
            }
        }
        return 0;
    }

    // ------------------------------------------------- 微信登陆函数 -------------------------------------------------
    // ------------------------------------------------- 微信登陆函数 -------------------------------------------------
    // ------------------------------------------------- 微信登陆函数 -------------------------------------------------
    // ------------------------------------------------- 微信登陆函数 -------------------------------------------------
    // ------------------------------------------------- 微信登陆函数 -------------------------------------------------
    // 用户数据与数据库同步，更新信息
    private function userInfoFromWechatSynchronize() {
        if($this->user['nickname']){
            $this->user['nickname'] = userTextEncode( $this->user['nickname'] );
        }
        $openid = $this->user['openid'];
        $wechat_data = $this->user;
        // $wechat_data[nickname] = userTextEncode($wechat_data[nickname]);
        // dump($wechat_data);
        // die();
        // $userInfo[nickname] = userTextEncode($userInfo[nickname]);
        //查找是否存在
        $user = $this->exist(array('openid'=>$openid));
        //登录成功
        if($user['state']){
            //session_set
            $user_id = $this->session_set($user['data']);
            //同步数据
            $where = array('user_id'=>$user_id);
            $user=db('user')->field('district_modified')->where($where)->find();
            $userInfo = $wechat_data;
            if ($user['district_modified']) {
                unset($userInfo['country']);
                unset($userInfo['province']);
                unset($userInfo['city']);
                unset($userInfo['district']);
            }
            $userInfo = array_change_key_case($userInfo, CASE_LOWER);
            db('user')->where($where)->update($userInfo);
            return ['state'=>1,'login'=>1];
        }
        //首次登陆(注册)
        $this->newUser($this->user);
        return array('state'=>1,'first'=>1);
    }
    // 用户通过base方法登录
    private function loginGetOpenId() {
        $wechat = config('wechat');
        $appid  = $wechat['APPID'];
        $secret = $wechat['APPSECRET'];
        $code = input("code");
//        dump($_SERVER);die;
        $get_token_url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid=' . $appid . '&secret=' . $secret . '&code=' . $code . '&grant_type=authorization_code';
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $get_token_url);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
        $res = curl_exec($ch);
        curl_close($ch);
        $json_obj = json_decode($res, true); // 根据openid和access_token查询用户信息
        $openid = $json_obj['openid'];
        return $json_obj;
    }
    public function loginBaseRedirect() {
        session("login_wechat",null);
        // unset($_SESSION['wechatLogin']);
        $openid = $this->loginGetOpenId();
        $openid = $openid['openid'];
        // 此处使用unionId机制获取用户信息
        $wechat = new Wechat;
        $access_token = $wechat->getAccessToken();
        $get_user_info_url = 'https://api.weixin.qq.com/cgi-bin/user/info?access_token=' . $access_token . '&openid=' . $openid . '&lang=zh_CN';
        $res = httpGet($get_user_info_url);
        $this->user = json_decode($res, true);
        // subscribe=1/0 如果用户关注，则直接获取用户相关信息，如果用户未关注，则用userinfo的登录方式请用户确认登录
        if (!isset($this->user['subscribe']) || !$this->user['subscribe']) {
            $userExist = $this->exist(array('openid'=>$openid));
            if($userExist['state']){
                $user = array(
                    'user_id'=>$userExist['data']['user_id'],
                );
                $this->session_set($user);
            }else{
                $this->loginInWechat('snsapi_userinfo');
                return;
            }
        }else{
            // 如果用户已关注，则成功登录，返回来路页面
            // 将用户数据同步至数据库
            // if($userExist[state]){
            $user_id = $this->userInfoFromWechatSynchronize();
            // }else{
            // $this->newUser($this->user);
            // }
        }
        $state = urldecode($_GET['state']);
        if(session('HTTP_REFERER')) {
            header('Location:'.session('HTTP_REFERER'));
        }else{
            header('Location:http://'.$_SERVER["HTTP_HOST"].$state);
        }
        die();
    }
    // 如果用户未关注公众号，则进入userinfo登录方法
    public function loginUserInfoRedirect() {
        session("login_wechat",null);
        // unset($_SESSION['wechatLogin']);
        $json_obj = $this->loginGetOpenId();
        $openid = $json_obj['openid'];
        $access_token = $json_obj['access_token'];
        $get_user_info_url = 'https://api.weixin.qq.com/sns/userinfo?access_token=' . $access_token . '&openid=' . $openid . '&lang=zh_CN';
        $res = httpGet($get_user_info_url);
        $this->user = json_decode($res, true);
        $user_id = $this->userInfoFromWechatSynchronize();
        $state = urldecode($_GET['state']);
        header('Location:http://' . $_SERVER['HTTP_HOST'] . $state);
        die();
    }
    private function loginInWechat($scope = "snsapi_base") {
        if(isset($_SERVER['HTTP_REFERER'])) {
            $a = substr($_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'],strpos($_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'],"}"));
            $a = str_replace('}','#',$a);
            session('HTTP_REFERER', $_SERVER['HTTP_REFERER'].$a);
        }
        $wechat = config('wechat');
        $APPID = $wechat['APPID'];
        if ($scope == 'snsapi_base') {
            $state = $_SERVER['REQUEST_URI'];
            $REDIRECT_URI = config("url") . '/login/wechat_base';
        } elseif ($scope == 'snsapi_userinfo') {
            $state = input('state');
            $REDIRECT_URI = config("url") . '/login/wechat_user_info';
        }
        $url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' . $APPID . '&redirect_uri=' . urlencode($REDIRECT_URI) . '&response_type=code&scope=' . $scope . '&state=' . urlencode($state) . '#wechat_redirect';
        header("Location:" . $url);
        die();
    }
    public function loginInXcx($code){
        if(!$code) return array('errormsg'=>'code missing');
        $url = "https://api.weixin.qq.com/sns/jscode2session?appid=".C('APPID')."&secret=".C('APPSECRET')."&js_code=".$code."&grant_type=authorization_code";
        $res = httpGet($url);

        // $res = "{\"session_key\":\"VuK0qPSwO+alxYE5MfBNAQ==\",\"expires_in\":2592000,\"openid\":\"o0rr50MNSeS4aW2SQcfSTJ_ZOEDQ\"}";
        // dump($res);
        $res = json_decode($res,true);
        if($res['errmsg']){
            $res['state']=0;
            $res['errormsg'] = explode(",",$res['errmsg'])[0];
            return $res;
        }
        // dump($res);
        $openid = $res['openid'];
        $info = array('openid'=>$openid);
        // dump($info);
        $exist = $this->exist($info);
        // dump($exist);
        if(!$exist['state']){
            $newUser = $this->newUser($info);
            // dump($newUser);
            $user_id = $newUser;
        }else{
            $user_id = $exist['data']['user_id'];
        }
        // dump($user_id);
        $user['user_id'] = $user_id;
        $this->session_set($user);
        $userInfo = $this->getInfoById($user_id);
        // dump($userInfo);
        $tel = $userInfo['tel'];
        $res['state'] = 1;
        $res['user_id'] = $user_id;
        if($tel) $res['tel'] = $tel;
        // $ret = array(state=>1,tel=>$tel,session_key=>$res[session_key]);
        //
        return $res;
    }
    public function wechatAutoLogin($notConfirm = false) {
        if ($this->user) {
            return;
        }
        if (!session('login_wechat') && isWeixin()) {
            $this->loginInWechat();
        }
    }
    // ------------------------------------------------- 对外支持合集 -------------------------------------------------
    // ------------------------------------------------- 对外支持合集 -------------------------------------------------
    // ------------------------------------------------- 对外支持合集 -------------------------------------------------
    // ------------------------------------------------- 对外支持合集 -------------------------------------------------
    // ------------------------------------------------- 对外支持合集 -------------------------------------------------
    // ------------------------------------------------- 对外支持合集 -------------------------------------------------
    // 检查是否已经登陆
    public function logined() {
        $s = session('user');
        if ($s && isset($s['user_id'])) {
            return 1;
        }
        return 0;
    }
    // 获取user表的id
    public function getUserId() {
        return $this->user['user_id'];
    }
    public function getOpenId($user_id = null) {
        $user_id = $user_id?$user_id:$this->user['user_id'];
        $where = array(
            'user_id' => $user_id,
            'state' => 1,
            'app_index' => $this->appIndex,
        );
        // dump($where);
        $res = db('user_openid')->where($where)->find();
        return $res['openid'];
    }
    // 获取名称
    public function getUserName($user = null) {
        if(!$user){
            $user = $this->user;
        }
        if (isset($user['user_name']) && $user['user_name']) {
            return $user['user_name'];
        }
        if (isset($user['real_name']) && $user['real_name']) {
            return $user['real_name'];
        }
        if (isset($user['nickname']) && $user['nickname']) {
            return $user['nickname'];
        }
        if (isset($user['tel']) && $user['tel']) {
            return "#" . $user['tel'];
        }
        if (isset($user['email']) && $user['email']) {
            return "#" . $user['email'];
        }
        if (isset($user['set_name']) && $user['set_name']) {
            return $user['set_name'];
        }
        return "user#".$user['user_id'];
    }
    public function setName($user_id,$newName){
        if(!$this->getUserId()) return ['state'=>0,'errormsg'=>'请登录'];
        if(!$user_id) return['state'=>0,'errormsg'=>'user_id missing'];
        $admin = new Admin;
        if($admin->exist($user_id)){
            if(!$admin->chief && !$admin->ultimate) return ['state'=>0,'errormsg'=>'authority incorrect, is admin'];
        }else{
            $is = $admin->is('client');
            if( !isset($is['state']) || !$is['state'] ) return ['state'=>0,'errormsg'=>'authority incorrect'];
        }
        $where = ['user_id'=>$user_id];
        $update = ['set_name'=>$newName];
        $res = db('user')->where($where)->update($update);
        if(!$res) return ['state'=>0,'errormsg'=>'update incorrect'];
        return ['state'=>1];
    }
    public function createByClientAdmin(){
        $admin = new Admin;
        $isClient = $admin->is('client');
        if(!$isClient['state']){
            return ['state'=>0,'errormsg'=>'authority incorrect'];
        }
        if(isset($isClient['chief']) && $isClient['chief']){
            return ['state'=>0,'errormsg'=>'chief incorrect'];
        }
        $user['join_time'] = time();
        $str = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
        $rand_id_exist = true;
        while((!isset($rand_id) || !$rand_id) && $rand_id_exist){
            $rand_id = substr(str_shuffle($str), 0, 32);
            $rand_id_exist = db('user')->where(array('rand_id'=>$rand_id))->find();
        }
        $user['rand_id'] = $rand_id;
        $user['from'] = session('from');
        $user['admin_user_id'] = $this->getUserId();
        $user['from'] = 'admin';
        $user_add = array_change_key_case($user, CASE_LOWER);
        $user_id = db('user')->insertGetId($user_add);
        if(!$user_id){
            return array('state'=>0,'errormsg'=>'new user database save error');
        }
        return ['state'=>1,'data'=>['user_id'=>$user_id]];
    }
    public function bindingTelByClientAdmin($client_user_id,$tel,$code){
        if(!$client_user_id){
            return ['state'=>0,'errormsg'=>'need user_id'];
        }
        if(!$tel){
            return ['state'=>0,'errormsg'=>'need tel'];
        }
        if(!$code){
            return ['state'=>0,'errormsg'=>'need code'];
        }
        $admin = new Admin;
        $isClient = $admin->is('client');
        if(!$isClient['state']){
            return ['state'=>0,'errormsg'=>'authority incorrect'];
        }
        if(isset($isClient['chief']) && $isClient['chief']){
            return ['state'=>0,'errormsg'=>'chief incorrect'];
        }
        $exist = $this->exist(['tel'=>$tel]);
        if($exist['state']){
            return ['state'=>0,'errormsg'=>'tel exist'];
        }
        $info = $this->getInfoById($client_user_id);
        if($info && isset($info['tel']) && $info['tel']){
            return ['state'=>0,'errormsg'=>'user has tel'];
        }
        $token = new Token;
        $data = ['content'=>$tel,'code'=>$code];
        $token = $token->check($demand='binding_tel',$data);
        if(!$token['state']){
            return $token;
        }
        $tel = $token['data']['content'];
        if(!$tel){
            return ['state'=>0,'errormsg'=>'tel error' ];
        }
        $insert = ['state'=>1,'tel'=>$tel,'user_id'=>$client_user_id,'create_time'=>time()];
        $res = db('user_tel')->insert($insert);
        if(!$res){
            return ['state'=>0,'errormsg'=>'database save error'];
        }
        return ['state'=>1 ];
    }

    public function password_set($data){
        $user_id = $this->getUserId();
        if(!$user_id) return ['errormsg'=>'请登录'];
        if(!isset($data['password'])){
            return ["state"=>0,'errormsg'=>'need new password'];
        }
        $newPassword = $data['password'];
        $where = ['state'=>1,'user_id'=>$user_id];
        $oldPassword = db('user_password')->field('password')->where($where)->find();
        if(isset($oldPassword['password'])){
            if(!isset($data['password_old'])){
                return ["state"=>0,'errormsg'=>'need old password'];
            }
            $oldPassword_input = $data['password_old'];
            if($oldPassword_input == $newPassword){
                return ['state'=>0,'errormsg'=>'old password same'];
            }
            $oldPassword_input = md5($oldPassword_input);
            $oldPassword = $oldPassword['password'];
            if($oldPassword != $oldPassword_input){
                return ['state'=>0,'errormsg'=>'old password error'];
            }
            $res = db('user_password')->where($where)->update(['state'=>0]);
            if(!$res) return ['state'=>0,'errormsg'=>'old password database update error'];
        }
        $reg = $this->password_reg;
        if(!preg_match($reg, $newPassword)) return ['state'=>0,'errormsg'=>'密码错误'];
        $newPassword = md5($data['password']);
        $insert = [
            'state'         => 1,
            'create_time'   => time(),
            'password'      => $newPassword,
            'user_id'       => $user_id,
        ];
        $res = db('user_password')->insert($insert);
        if(!$res) return ['state'=>0,'errormsg'=>'修改失败'];
        $this->session_set();
        return ['state'=>1];

    }
    public function password_reset($data){
        $tel = $data['tel'];
        if(!isset($data['code'])) return ['state'=>0,'errormsg'=>'请输入验证码'];
        if(!$data['password']) return ['state'=>0,'errormsg'=>'请输入密码'];
        if(!$tel){
            $user_id = $this->getUserId();
            if(!$user_id) return ['errormsg'=>'not login'];
            $where = ['user_id'=>$user_id,'state'=>1];
            $res = db('user_tel')->where($where)->field('tel')->find();
            if(!isset($res['tel'])) return ['state'=>0,'errormsg'=>'电话号码错误'];
            $tel = $res['tel'];
        }else{
            $user_id = db("user_tel")->where("tel = $tel and state = 1")->find();
            if(!$user_id) return ['state'=>0,'errormsg'=>'该手机号码未注册'];
            $user_id = $user_id['user_id'];
            $where = ['user_id'=>$user_id,'state'=>1];
        }
        $code = $data['code'];
        $token = new Token;
        $token = $token->check('login_sms',array(
            'code' =>$code,
            'content' =>$tel
        ));
        if(!$token['state']){
            return $token;
        }
        $res = db('user_password')->where($where)->update(['state'=>0]);
        if(!$res) return ['state'=>0,'errormsg'=>'old password database update error'];
        $pass['password'] = md5($data['password']);
        $pass['create_time'] = time();
        $pass['user_id'] = $user_id;
        $pass['state'] = 1;
        $p = db('user_password')->insert($pass);
        if(!$p) return ['state'=>0,'errormsg'=>'重置失败'];
        $this->session_set();
        return ['state'=>1];
    }
    public function password_reset_send($tels=null){
        $tel = $tels;
        if(!$tel) {
            $user_id = $this->getUserId();
            if (!$user_id) return ['errormsg' => 'not login'];
            //获取电话
            $where = ['user_id' => $user_id, 'state' => 1];
            $tel = db('user_tel')->field('tel')->where($where)->find();
            if (!$tel) return ['user tel error'];
            $tel = $tel['tel'];
        }else{
            //查询手机号码是否注册
            $user_id = db("user_tel")->where("tel = $tel and state = 1")->find();
            if(!$user_id) return ['state'=>0,'errormsg'=>'该手机号码未注册'];
        }
        //获取token
        $code = session("sms_login_token");
        if(!$code){
            $token = new Token;
            $res = $token->add('login_sms',[
                'content'=>$tel
            ]);
            if(!isset($res['state']) || !$res['state']) return $res;
            $code = $res['data']['code'];
            session('sms_login_token',$code);
        }
        //发送短信
        $sms = new Sms;
        $res = $sms->send('login',['tel'=>$tel,'code'=>$code]);
        if(!isset($res['state']) || !$res['state']) return $res;
        session('sms_login_token',null);
        return $res;
    }

    // 修改用户相关信息
    public function modify($data){
        if (!$this->logined()) {
            return array('state' => 0,'errormsg' => '请登录ed');
        }
        $config = getConfig("user_modify");
        if(!$config){
            return array('state'=>0,'errormsg'=>'config error');
        }
        foreach($data as $k => $v){
            if($k == 'province'){
                $a = explode(',',$data['province']);
                $data['province'] = $a[0];
                $data['city'] = $a[1];
            }
            if(!array_key_exists($k,$config)){
                return array('state'=>0,'errormsg'=>'key not allowed');
            }
            if(isset($config[$k]['reform'])){
                $data[$k] = $config[$k]['reform']($v);
            }
            if(isset($config[$k]['reg'])){
                $reg = $config[$k]['reg'];
                if(!preg_match($reg,$v)){
                    return array('state'=>0,'errormsg'=>"value match incorrect");
                }
            }
        }
        $user_id = $this->getUserId();
        $where = ['user_id'=>$user_id];
        // dump($data);
        // 检查字段是否允许修改
//        $this->checkData($data);
        // 检查已登录
        // 如果用户主动修改省市区信息，则保留用户修改值
        // 如果没有修改，则使用微信接收地址
        if (!empty($data['province']) || !empty($data['city']) || !empty($data['district']) || !empty($data['country'])) {
            $data['district_modified'] = 1;
        }
        // 时间格式转换
        // $data['BIRTH'] = time($data['BIRTH']);
        $res = db('user')->where($where)->update($data);
        $action = new Action;
        // 记录action表动作行为
        if ($res) {
            foreach ($data as $key => $value) {
                $action->add('user_modify', $key, $value);
            }
            $this->lastAction();
            if($this->config["SESSION_INFO"]){
                session("user",["user_id"=>$user_id]);
            }
            $ret = array('state' => 1 );
        } else {
            $ret = array('state' => 0, 'errormsg' => 'database error', 'errorcode' => 'u18971795');
        }
        ////var_dump(M()->getLastSql());
        return $ret;
    }
    public function getInfoById($user_id){
        if(!$user_id){
            return false;
        }
        if(is_array($user_id)){
            $user_ids = implode(",", $user_id);
            $where = " user_id in ($user_ids) ";
        }else{
            // $user_ids = $user_id;
            $where = " user_id = $user_id ";
        };
        $users = db('user')->where($where)->select();
        if(!$users){
            return false;
        }
        $where = ["state"=>1];
        foreach ($users as $index => $user) {
            $user['nickname'] = userTextDecode($user['nickname']);
            foreach ($this->method as $value) {
                $where_use = $where;
                $where_use["user_id"] = $user['user_id'];
                if($value == 'openid'){
                    $where_use['app_index'] = $this->appIndex;
                }
                $res = db('user_'.$value)->field($value)->where($where_use)->find();
                if($res){
                    $user[$value] = $res[$value];
                }
            }
            if(isset($user['openid']) && $user['openid']){
                $user['openid'] = 1;
            }
            if(isset($user['tel'])){
                $tel = $user['tel'];
                $user['tel'] = substr($tel,0,3)."*****".substr($tel,8);
            }
            if(isset($user['email'])){
                $email = $user['email'];
                $user['email'] = substr($email,0,3)."*****".strstr($email,"@");
            }
            if(isset($user['birth']) && $user['birth']){
                $user['birth'] = date("Y-m-d",$user['birth']);
            }
            $user['user_name'] = $this->getUserName($user);
            $users[$index] = $user;
        }
        if(!is_array($user_id)){
            $users = isset($users[0])?$users[0]:null;
        }else{
            $users_idkey = [];
            foreach ($users as $key => $value) {
                $users_idkey[$value['user_id']] = $value;
            }
            return $users_idkey;
        }
        return $users;
    }
    //已登录的情况下获取info信息
    public function getInfo($reload = false){return $this->info($reload);}
    public function info($reload = false){
        if(!$this->logined()){
            return ['errormsg'=>'请登录'];
        }
        if(!$reload && $this->user){
            return ['state'=>1,'data'=>$this->user];
        }
        $user = session("user");
        $user_id = $user['user_id'];
        if(!$user_id){
            return ['errormsg'=>'user_id missing'];
        }
        $where = array('user_id'=>$user_id);
        $user = db('user')->where($where)->find();
        if(!$user){
            return ['errormsg'=>'user bd empty'];
        }
        $user['nickname'] = isset($user['nickname'])?userTextDecode($user['nickname']):"";
        $where['state'] = 1;
        foreach ($this->method as $value) {
            $where_use = $where;
            if($value == 'openid'){
                $where_use['app_index'] = $this->appIndex;
            }
            $res = db('user_'.$value)->field($value)->where($where_use)->find();
            if($res){
                $user[$value] = $res[$value];
            }
        }
        if(isset($user['openid']) && $user['openid']){
            $user['openid'] = 1;
        }
        if(isset($user['tel'])){
            $tel = $user['tel'];
            $user['tel'] = substr($tel,0,3)."*****".substr($tel,8);
        }
        if(isset($user['email'])){
            $email = $user['email'];
            $user['email'] = substr($email,0,3)."*****".strstr($email,"@");
        }
        if(isset($user['birth']) && $user['birth']){
            $user['birth'] = date("Y-m-d",$user['birth']);
        }
        $password = db('user_password')->where($where)->find();
        if($password) $user['password'] = 1;
        $this->user = $user;
        $this->user['user_name'] = $this->getUserName();
        return ['state'=>1,'data'=>$this->user];
    }
    // 记录用户最新动作时间
    public function lastAction() {
        $user_id = $this->getUserId();
        db('user')
            ->where(array('user_id'=>$user_id))
            ->update(array('last_action' => time()));
    }
    // ------------------------------------------------- 登陆方式合集 -------------------------------------------------
    // ------------------------------------------------- 登陆方式合集 -------------------------------------------------
    // ------------------------------------------------- 登陆方式合集 -------------------------------------------------
    // ------------------------------------------------- 登陆方式合集 -------------------------------------------------
    // ------------------------------------------------- 登陆方式合集 -------------------------------------------------
    //method : account,wechat,tel,email
    public function login($method,$info){
        switch ($method) {
            case 'account':
                if($this->logined()){
                    return array('state'=>0,'errormsg'=>'already logined');;
                }
                //没有输入账号
                if(!(isset($info['account']))){
                    return array('state'=>0,'errormsg'=>'need account');
                }
                $account = $info['account'];
                //没有输入密码
                // dump($info);
                if(!isset($info['password'])){
                    return array('state'=>0,'errormsg'=>'need password');
                }
                $password_input = $info['password'];
                //先找tel
                $user = $this->exist(array('tel'=>$account));
                if(!isset($user['state']) || !$user['state']){
                    //
                    $user = $this->exist(array('email'=>$account));
                }
                //没找到
                if(!isset($user['state']) || !$user['state']){
                    return array('state'=>0,'errormsg'=>'account not exist');
                }
                //根本就没有密码
                $user_id = $user['data']['user_id'];
                $where = ['user_id'=>$user_id,'state'=>1];
                $password = db('user_password')->where($where)->field('password')->find();
                if(!isset($password['password'])) return ['state'=>0,'errormsg'=>'未设置密码'];
                //密码错了
                $password = $password['password'];
                if($password != md5($password_input)){
                    return array('state'=>0,'errormsg'=>'密码错误');
                }
                if(0){
                    return ['state'=>0,'errormsg'=>'account login invalid'];
                    //成功 把账号存入session
                }
                $this->session_set(['user_id'=>$user_id,'auto'=>$info['auto']]);
                return array('state'=>1);
                break;
            // case 'wechat_confirm':
            //     if(!$user_id = $this->getUserId()){
            //         return array('state'=>0,'errormsg'=>'need user_id');
            //     }
            //     if(!$code = $info['code']){
            //         return array('state'=>0,'errormsg'=>'need code');
            //     }
            //     $data = array('code'=>$code,'content'=>$user_id);
            //     $token = new Token;
            //     $respond = $token->respond("login_wechat", $data);
            //     session('user',null);
            //     cookie('auto', null);
            //     // $this->logout();
            //     return $respond;
            // break;
            case 'wechat':
                if($this->getOpenId()){
                    return array('state'=>0 ,'errormsg'=>'already logined');
                }
                if(!$code = $info['code']){
                    return array('state'=>0,'errormsg'=>'need code');
                }
                $data = array('code'=>$code);
                $token = new Token;
                $token = $token->check("login_wechat", $data);
                if(!$token['state']){
                    return $token;
                }
                $user_id = $this->getUserId();
                $wx_user_id = $token['data']['content'];
                $user = array('user_id'=>$wx_user_id);
                //绑定行为
                if($user_id){
                    if($user_id == $wx_user_id){
                        return array('state'=>0,'errormsg'=>'user_id same');
                    }else{
                        $res = $this->binding(array('wx_user_id'=>$wx_user_id));
                        return $res;
                    }
                }
                $this->session_set($user);
                return array('state'=>1,'login'=>1);
                break;
            case 'tel':
                //没有输入电话
                if(!($tel = $info['tel'])){
                    return array('state'=>0,'errormsg'=>'need tel');
                }
                //没有输入code
                if(!($code = $info['code'])){
                    return array('state'=>0,'errormsg'=>'need code');
                }
                $token = new Token;
                $token = $token->check('login_sms',array(
                    'code' =>$code,
                    'content' =>$tel
                ));
                // dump($token);
                if(!$token['state']){
                    return $token;
                }
                $tel = $token['data']['content'];
                //绑定行为
                if($this->logined()){
                    $res = $this->binding(array('tel'=>$tel));
                    return $res;
                }
                // dump('start');
                $user = $this->exist(array('tel'=>$tel));
                //登录成功
                if($user['state']){
                    // dump($user);
                    $this->session_set($user['data']);
                    return array('state'=>1,'login'=>1);
                }
                //首次登陆(注册)
                $this->newUser($user = array('tel'=>$tel));
                return array('state'=>1,'first'=>1);
                break;
            case 'email':
                //没有输入code
                if(!($code = $info['code'])){
                    return array('state'=>0,'errormsg'=>'need code');
                }
                $token = new Token;
                $token = $token->check('login_email',array(
                    'code' =>$code,
                ));
                if(!$token['state']){
                    return $token;
                }
                $email = $token['data']['content'];
                $email_user_id = $token['data']['user_id'];
                //绑定行为
                if($email_user_id){
                    $this->session_set(array('user_id'=>$email_user_id));
                    $res = $this->binding(array('email'=>$email));
                    return $res;
                }
                $user = $this->exist(array('email'=>$email));
                //登录成功
                if($user['state']){
                    // dump($user);
                    $this->session_set($user['data']);
                    return array('state'=>1,'login'=>1);
                }
                //首次登陆(注册)
                $this->newUser($user = array('email'=>$email));
                return array('state'=>1,'first'=>1);
                break;
            case 'auto':
                break;
            default:
                return array('state'=>0,'errormsg'=>'login method error','data'=>array('account','wechat_confirm','tel','email','auto')) ;
        }
    }


    //添加证件照
    public function photo_add($url,$type)
    {
        if(!$this->getUserId()) return ['state'=>0,'errormsg'=>'请登录'];
        if(!$url) return ['state'=>0,'errormsg'=>'参数错误'];
        if($type){
            $data['id_photo_face'] = $url;
        }else{
            $data['id_photo_back'] = $url;
        }
        $user_id = $this->getUserId();
        //判断是否已经存在
        $info = db('user_photo')->where("user_id = $user_id and state = 1")->find();
        if($info) {
            $res = db('user_photo')->where("user_id = $user_id and state = 1")->update($data);
            if(!$res) return ['state'=>0,'errormsg'=>'添加失败'];
            return ['state'=>1,'errormsg'=>'成功'];
        }
        $data['user_id'] = $this->getUserId();
        $data['state'] = 1;
        $data['create_time'] = time();
        $res = db('user_photo')->insert($data);
        if(!$res) return ['state'=>0,'errormsg'=>'添加失败'];
        return ['state'=>1,'errormsg'=>'成功'];
    }
    //删除
    public function photo_remove($photo_id)
    {
        if(!$this->getUserId()) return ['state'=>0,'errormsg'=>'请登录'];
        if(!$photo_id) return ['state'=>0,'errormsg'=>'请选择一张照片'];
        $user_id = $this->getUserId();
        $res = db('user_photo')->where("$photo_id = photo_id and user_id = $user_id");
        if(!$res) return ['state'=>0,'errormsg'=>'删除失败'];
        return ['state'=>1,'errormsg'=>'成功'];
    }
    //照片列表
    public function photo_info()
    {
        if(!$this->getUserId()) return ['state'=>0,'errormsg'=>'请登录'];
        $user_id = $this->getUserId();
        $info = db('user_photo')->where("user_id = $user_id and state = 1")->find();
        if(!$info) return ['state'=>1,'data'=>[]];
        return ['state'=>1,'data'=>['info'=>$info]];
    }
}
